package middleware

import (
	"gitee.com/DonHz/simple-blog-system/config"
	"gitee.com/DonHz/simple-blog-system/util/jwtx"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Auth() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		loginUid:=GetLoginUid(ctx)
		if loginUid<=0 {
			ctx.String(http.StatusForbidden, "auth failed")
			ctx.Abort()
		}
		ctx.Set("uid", loginUid)
		ctx.Next()
	}
}

func GetLoginUid(ctx *gin.Context) int64 {
	// 方案一：由客户端手动往request header中添加auth_token
	token:=ctx.Request.Header.Get("auth_token")
	return GetUidFromJWT(token)
}

func GetUidFromJWT(token string) int64 {
	_,payload, err:= jwtx.VerifyJWT(token, config.JWT_SECRET)
	if err!=nil{
		return 0
	}
	for k, v:=range payload.UserDefined{
		if k=="uid" {
			return int64(v.(float64))
		}
	}
	return 0
}
